package services
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;
	
	import mx.controls.Alert;
	
	import org.robotlegs.mvcs.Actor;
	
	public class ServiceFile extends Actor implements IServiceFile
	{
		
		private var file:File = File.desktopDirectory;
		
		
		public function readFile(path:String):ByteArray
		{
			var data:ByteArray = new ByteArray();
			var f:File = new File(path);
			var stream:FileStream = new FileStream();
			stream.open(f, FileMode.READ);
			stream.readBytes(data);
			stream.close();
			return data;
		}
		
		public function writeFile(path:String, data:ByteArray, extension:String = null):Boolean
		{
			var f:File = new File(path);
			
			try{
				if (f.exists && !f.isDirectory){
					f.deleteFile();
				}
				
				if (extension != null){
					if (f.extension != extension){
						f = new File(f.nativePath + "." + extension);
					}
				}
				
				var stream:FileStream = new FileStream();
				stream.open(f, FileMode.WRITE);
				stream.writeBytes(data);
				stream.close();
				return true;
			}catch(e:Error){
				Alert.show(e.message);
				return false;
			}
			return false;
		}
		
		public function fileExists(path:String):Boolean
		{
			var f:File = new File(path);
			return f.exists;
		}
		
		public function getFileName(path:String) : String
		{
			var f:File = new File(path);
			return f.name;
		}
		
		public function getFileExtension(path:String) : String
		{
			var f:File = new File(path);
			return f.extension;
		}
		
		public function isDirectory(path:String):Boolean
		{
			var f:File = new File(path);
			return f.isDirectory;
		}
		
	}
}